<template>
    <div class="colorable-index-container"
        :class="{'cursor-pointer': updatable, 'cursor-default':!updatable}"
        :title="updatable ? '点击设置颜色' : undefined"
        @click="toggleColorPicker">
        <div class="index" :style="indexStyle">{{ index + 1 }}</div>
        <el-color-picker ref="colorPicker" v-model="model" :predefine="predefineColors"/>
    </div>
</template>

<script>
export default {
    name: 'ColorableIndex',
    props: {
        index: {
            type: Number,
            required: true,
        },
        color: {
            type: String,
            default: '',
        },
        updatable: Boolean,
    },
    emits: ['update:color'],
    data() {
        return {
            model: this.color,
        };
    },
    computed: {
        predefineColors() {
            const style = getComputedStyle(document.documentElement);
            return [
                style.getPropertyValue('--el-color-primary').trim(),
                style.getPropertyValue('--el-color-success').trim(),
                style.getPropertyValue('--el-color-warning').trim(),
                style.getPropertyValue('--el-color-danger').trim(),
                style.getPropertyValue('--el-color-info').trim(),
                '#FF0000', // 红
                '#FF7F00', // 橙
                '#FFFF00', // 黄
                '#00FF00', // 绿
                '#00FFFF', // 青
                '#0000FF', // 蓝
                '#8B00FF', // 紫
            ];
        },
        indexStyle() {
            if (!this.model) {
                return {};
            }
            // 将十六进制颜色转换为 rgba
            const rgb = this.model.match(/\w\w/g).map(x => parseInt(x, 16));
            return {
                color: this.model,
                borderColor: this.model,
                backgroundColor: `rgba(${rgb[0]}, ${rgb[1]}, ${rgb[2]}, 0.1)`,
            };
        },
    },
    watch: {
        color(val) {
            this.model = val;
        },
        model(val) {
            this.$emit('update:color', val);
        },
    },
    methods: {
        toggleColorPicker() {
            if (this.updatable) {
                this.$refs.colorPicker.show();
            }
        },
    },
}
</script>

<style lang="scss">
.colorable-index-container {
    position: relative;
    display: inline-block;
    text-align: center;

    .index {
        padding: 0 7px;
        border: 1px solid transparent;
        border-radius: 4px;
        width: fit-content;

        &:hover {
            opacity: 0.8;
        }
    }

    .el-color-picker {
        position: absolute;
        width: 0;
        height: 0;

        .el-color-picker__trigger {
            display: none;
        }
    }
}
</style>
